package com.jfinal.kit;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * 配置添加路径判断区分绝对路径、相对路径、classpath、webjars。
 *
 * 绝对路径    c://xxx/xxx
 * 相对路径    static/xxx/xx
 * classpath classpath:net/dreamlu/assets/test.js
 * webjars   webjars:/webjars/jquery/3.1.1-1/jquery.min.js
 * http https
 *
 * @author L.cm
 * email: 596392912@qq.com
 * site:http://www.dreamlu.net
 * @date 2017年3月22日下午8:32:08
 */
public class ResourceKit {
	private static final String HTTP_REGEX = "^https?://.+$";

	// webJar读取
	private static InputStream getByWebjars(String webjarPath) throws IOException {
		String webjarsResourceURI = "/META-INF/resources" + webjarPath;
		return getByClassPath(webjarsResourceURI);
	}

	// 类路径读取
	private static InputStream getByClassPath(String classPathURI) throws IOException {
		return ResourceKit.class.getResourceAsStream(classPathURI);
	}

	// http路径读取
	private static InputStream getByHttp(String url) throws IOException {
		URLConnection connection = new URL(url).openConnection();
		connection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
		return connection.getInputStream();
	}

	/**
	 * 读取js，css文件
	 * @param path 路径
	 * @return 文件内容
	 * @throws IOException
	 */
	public static InputStream getResource(String path) throws IOException {
		if (path.startsWith("webjars:")) {
			String webJarPath = repairPath(path.substring(8, path.length()));
			return getByWebjars(webJarPath);
		} else if (path.startsWith("classpath:")) {
			String classpath = repairPath(path.substring(10, path.length()));
			return getByClassPath(classpath);
		} else if (path.matches(HTTP_REGEX)) {
			return getByHttp(path);
		}
		String filePath;
		if (PathKit.isAbsolutePath(path)) {
			filePath = path;
		} else {
			String webRoot = PathKit.getWebRootPath();
			filePath = webRoot + File.separator + path;
		}
		File file = new File(filePath);
		if (!file.exists()) {
			throw new FileNotFoundException(file.getAbsolutePath());
		}
		return new FileInputStream(file);
	}

	/**
	 * 路径修复
	 * @param path
	 * @return
	 */
	private static String repairPath(String path) {
		if (!path.startsWith("/")) {
			path = "/" + path;
		}
		return path;
	}

}
